package com.motong.gongdan.controller.system;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.motong.gongdan.config.ResponseData;
import com.motong.gongdan.config.auth.UserLoginToken;
import com.motong.gongdan.entity.PrintTemplate;
import com.motong.gongdan.service.*;
import com.motong.gongdan.util.FileUtil;
import com.motong.gongdan.util.LoginUtil;
import com.motong.gongdan.util.OwnUtil;
import com.motong.gongdan.util.TimeUtil;
import com.motong.gongdan.vo.system.ExcelTemplate.vo.ExcelTemplateDataVo;
import com.motong.gongdan.vo.system.printTemplate.query.ListQuery;
import com.motong.gongdan.vo.system.printTemplate.vo.ExportDataByModelVo;
import com.motong.gongdan.vo.system.printTemplate.vo.ListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "打印模板")
@RestController
@RequestMapping("/sys/printTemplate")
public class PrintTemplateController {

    @Resource
    private PrintTemplateService printTemplateService;

    @Resource
    private WorkOrderService workOrderService;

    @Resource
    private UserService userService;

    @Resource
    private StockMsgService stockMsgService;

    @Resource
    private CommonService commonService;

    @UserLoginToken
    @ApiOperation("获取打印模板列表")
    @PostMapping("/list")
    public ResponseData<Page<ListVo>> list(@RequestBody(required = false) ListQuery listQuery) {
        listQuery = Objects.isNull(listQuery) ? new ListQuery() : listQuery;
        return ResponseData.success(printTemplateService.getList(listQuery));
    }

    /**
     * 上传打印模板
     *
     * @param belongModule 所属模块
     * @param templateType 模板类型(0 系统模板,1 公共模板)
     */
    @UserLoginToken
    @ApiOperation("上传打印模板")
    @PostMapping("/uploadTemplate")
    public ResponseData<String> uploadTemplate(MultipartFile file, @RequestParam(required = false, defaultValue = "0") Integer belongModule, @RequestParam(required = false, defaultValue = "1") Integer templateType) {
        Integer loginUserId = LoginUtil.getLoginUserId();
        String preFix = "/service/file/printTemplate/" + (templateType == 0 ? "" : (TimeUtil.getDateDefaultStringTwo(new Date()) + "/"));
        String url = FileUtil.uploadFile(file, preFix, Objects.requireNonNull(file.getOriginalFilename()).substring(0, file.getOriginalFilename().indexOf(".")) + (templateType == 0 ? "" : "-" + new Date().getTime()));
        if (!StringUtils.hasLength(url)) {
            return ResponseData.fail("上传打印模板失败!");
        }
        PrintTemplate printTemplate = new PrintTemplate().setBelongModule(belongModule).setTemplateType(templateType).setCreateTime(new Date()).setCreateUser(loginUserId)
                .setTemplateName(url.substring(url.lastIndexOf("/") + 1)).setTemplatePath(url);
        printTemplateService.save(printTemplate);
        return ResponseData.success("上传成功!");
    }

    /**
     * 下载模板
     *
     * @param id 模板id
     */
    @UserLoginToken
    @ApiOperation("下载打印模板")
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(@RequestParam Integer id, HttpServletResponse response) throws IOException {
        PrintTemplate printTemplate = printTemplateService.getById(id);
        OwnUtil.fileToResponse(new File(printTemplate.getTemplatePath()), response);
    }


    /**
     * 删除打印模板
     *
     * @param id 模板id
     */
    @UserLoginToken
    @ApiOperation("删除打印模板")
    @PostMapping("/delete/{id}")
    public ResponseData<String> delete(@PathVariable("id") Integer id) {
        PrintTemplate printTemplate = printTemplateService.getById(id);
        if (Objects.isNull(printTemplate) || !new File(printTemplate.getTemplatePath()).delete()) {
            return ResponseData.fail("删除文件失败!");
        }
        printTemplateService.removeById(id);
        return ResponseData.success("删除成功!");
    }

    /**
     * 根据模板打印数据
     */
//    @UserLoginToken
//    @ApiOperation("根据模板打印数据")
//    @PostMapping("/exportDataByModel")
//    public void exportByTemplate(@RequestBody ExportDataByModelVo exportDataByModelVo, HttpServletResponse response) throws IOException {
//        List<Integer> workIdList = new ArrayList<>();
//        if (StringUtils.hasLength(exportDataByModelVo.getWorkIds())) {
//            List<Integer> workIds = Arrays.stream(exportDataByModelVo.getWorkIds().split(",")).filter(StringUtils::hasLength).map(Integer::valueOf).collect(Collectors.toList());
//            workIdList.addAll(workIds);
//        }
//        if (Objects.nonNull(exportDataByModelVo.getWorkId())) {
//            workIdList.add(exportDataByModelVo.getWorkId());
//        }
//        // 获取模板信息
//        PrintTemplate printTemplate = printTemplateService.getById(exportDataByModelVo.getId());
//        InputStream bufferedInputStream = null;
//        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//             XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(printTemplate.getTemplatePath()))) {
//            // 去除模板帮助
//            if (workbook.getNumberOfSheets() > 1) {
//                workbook.removeSheetAt(0);
//            }
//            for (int i = 0; i < workIdList.size() - 1; i++) {
//                workbook.cloneSheet(0);
//            }
//            workbook.write(byteArrayOutputStream);
//            InputStreamSource byteArrayResource = new ByteArrayResource(byteArrayOutputStream.toByteArray());
//            bufferedInputStream = byteArrayResource.getInputStream();
//            //写入文件
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(printTemplate.getTemplateName(), "UTF-8"));
//            try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(bufferedInputStream).build()) {
//                FillConfig fillConfig = FillConfig.builder().forceNewRow(true).build();
//                AtomicReference<Integer> sheetNo = new AtomicReference<>(0);
//                // 写入多个sheet
//                workIdList.forEach(workCode -> {
//                    //获取数据
//                    List<Map<String, Object>> listData;
//                    Map<String, Object> singleData;
//                    //工单
//                    if (printTemplate.getBelongModule() == 0) {
//                        singleData = workOrderService.getExportData(workCode);
//                        String qrPath = singleData.getOrDefault("qr", "").toString();
//                        if (StringUtils.hasLength(qrPath)) {
//                            String replace = "https://mtgongdan.com".concat(qrPath.replace("/service", ""));
//                            try {
//                                singleData.put("qr", new URL(replace));
//                            } catch (MalformedURLException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                        listData = workOrderService.getExportProcessList(workCode);
//                    } else {
//                        singleData = stockMsgService.getExportData(workCode);
//                        listData = stockMsgService.getExportProductList(workCode);
//                    }
//                    singleData.put("handleName", userService.getById(LoginUtil.getLoginUserId()).getName());
//                    singleData.put("handleTime", DateUtil.now());
//                    WriteSheet writeSheet = EasyExcel.writerSheet().sheetNo(sheetNo.getAndSet(sheetNo.get() + 1)).build();
//                    excelWriter.fill(listData, fillConfig, writeSheet);
//                    excelWriter.fill(singleData, writeSheet);
//                });
//
//                if (workIdList.size() > 1) {
//                    // 合并sheet
//                    Workbook sourceWorkbook = excelWriter.writeContext().writeWorkbookHolder().getWorkbook();
//                    XSSFWorkbook targetWorkbook = new XSSFWorkbook();
//                    Sheet targetSheet = targetWorkbook.createSheet();
//                    int secondSourceSheetLen = 0;
//                    SXSSFWorkbook sw = (SXSSFWorkbook) sourceWorkbook;
//                    for (int i = 0; i < workIdList.size(); i++) {
//                        XSSFSheet sourceSheet = sw.getXSSFWorkbook().getSheetAt(i);
//                        POIUtil.copySheet(targetSheet, sourceSheet, targetWorkbook, sourceWorkbook, secondSourceSheetLen);
//                        secondSourceSheetLen += sourceSheet.getPhysicalNumberOfRows() + 1;
//                    }
//                    excelWriter.writeContext().writeWorkbookHolder().setWorkbook(targetWorkbook);
//                }
//                excelWriter.finish();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (Objects.nonNull(bufferedInputStream)) {
//                bufferedInputStream.close();
//            }
//        }
//    }


    /**
     * 根据模板打印数据
     */
    @UserLoginToken
    @ApiOperation("根据模板打印数据")
    @PostMapping("/exportDataByModel")
    public void exportByTemplate(@RequestBody ExportDataByModelVo exportDataByModelVo, HttpServletResponse response) {
        List<Integer> workIdList = new ArrayList<>();
        if (StringUtils.hasLength(exportDataByModelVo.getWorkIds())) {
            List<Integer> workIds = Arrays.stream(exportDataByModelVo.getWorkIds().split(",")).filter(StringUtils::hasLength).map(Integer::valueOf).collect(Collectors.toList());
            workIdList.addAll(workIds);
        }
        if (Objects.nonNull(exportDataByModelVo.getWorkId())) {
            workIdList.add(exportDataByModelVo.getWorkId());
        }
        // 获取模板信息
        PrintTemplate printTemplate = printTemplateService.getById(exportDataByModelVo.getId());
        List<ExcelTemplateDataVo> excelData = new ArrayList<>();
        if (Objects.isNull(printTemplate) || !StringUtils.hasLength(printTemplate.getTemplatePath())) {
            return;
        }
        // 获取数据
        workIdList.forEach(workCode -> {
            //获取数据
            List<Map<String, Object>> listData;
            Map<String, Object> singleData;
            //工单
            if (printTemplate.getBelongModule() == 0) {
                singleData = workOrderService.getExportData(workCode);
                String qrPath = singleData.getOrDefault("qr", "").toString();
                if (StringUtils.hasLength(qrPath)) {
                    String replace = "https://mtgongdan.com".concat(qrPath.replace("/service", ""));
                    try {
                        singleData.put("qr", new URL(replace));
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                }
                listData = workOrderService.getExportProcessList(workCode);
            } else {
                singleData = stockMsgService.getExportData(workCode);
                listData = stockMsgService.getExportProductList(workCode);
            }
            singleData.put("handleName", userService.getById(LoginUtil.getLoginUserId()).getName());
            singleData.put("handleTime", DateUtil.now());
            excelData.add(new ExcelTemplateDataVo().setSingleData(singleData).setListData(listData));
        });
        commonService.exportExcelData(response, printTemplate.getTemplatePath(), printTemplate.getTemplateName(), excelData);
    }
}
